﻿<%@ WebHandler Language="C#" Class="HandlerMainPage" %>

using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using Newtonsoft.Json;
using System.Collections.Generic;

public class HandlerMainPage : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {

        List<ctr> ctrs = new List<ctr>();
        string strConn = UserClass.strconn;
        using (SqlConnection conn = new SqlConnection(strConn))
        {
            string strCmd = @"SELECT id, CONVERT(NUMERIC(8,1),ROUND(pctTemp*100,3)) AS percentage FROM
                                            (SELECT id, ([count]+.0)/(SELECT SUM([count]) FROM main_page_ctr) AS pctTemp
                                            FROM main_page_ctr) AS temp";
            using (SqlCommand cmd = new SqlCommand(strCmd, conn))
            {
                conn.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {       
                    int rId = Convert.ToInt32(reader["id"]);
                    decimal rPercentage = Convert.ToDecimal(reader["percentage"]);
                    if(Convert.ToInt32(reader["id"])<=40){
                        ctr ctr = new ctr();
                        ctr.id = rId;
                        ctr.percentage = rPercentage;
                        ctrs.Add(ctr);
                    }
                    else
                    {
                        ctrs[39].percentage = ctrs[39].percentage + rPercentage;
                    }
                }
                context.Response.ContentType = "application/json";
                context.Response.Write(JsonConvert.SerializeObject(ctrs));
                conn.Close();
            }
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}